package pogvue.datamodel;

import pogvue.io.*;
import java.util.*;
import java.io.*;

public class KmerIndex {
    int count;
    String kmer;

    Vector coords;

    public KmerIndex(String kmer) {
       this.kmer = kmer;
       count = 0;
       coords = new Vector();
    }

    public void addKmer(String chr, int start) {
        String pos = chr + "." + start;
 
        coords.addElement(pos);
        count++;
    }

    public Vector getCoords() {
       return coords;
    }

    public int getCount() {
	return count;
    }

    public String getKmer() {
	return kmer;
    }

    public static void print_kmers(Hashtable kmers1,Hashtable kmers2, int thresh) {
	
	int len = -1;

	int tot1 = 0;
	
	Enumeration en = kmers1.keys();
	
	while (en.hasMoreElements()) {
	    KmerIndex tmp = (KmerIndex)(kmers1.get(en.nextElement()));
	    tot1 += tmp.getCount();
	    len = tmp.getKmer().length();
	}
	
	int tot2 = 0;
	
	en = kmers2.keys();
	
	while (en.hasMoreElements()) {
	    KmerIndex tmp = (KmerIndex)(kmers2.get(en.nextElement()));
	    tot2 += tmp.getCount();
	}
		

	
	int[] counts = new int[kmers1.size()];
	KmerIndex[] kindex = new KmerIndex[kmers1.size()];

	en = kmers1.keys();

	int i = 0;

	while (en.hasMoreElements()) {
	    String    kmer = (String)en.nextElement();
	    KmerIndex km   = (KmerIndex)kmers1.get(kmer);

	    counts[i] = km.getCount();
	    kindex[i] = km;
	    i++;
	}

	pogvue.util.QuickSort.sort(counts,kindex);

	i = 0;

	int num = (int)(Math.pow(4.0,1.0*len));

	while (i < kindex.length) {
	    if (kindex[i].getCount() > thresh) {
		String kmer = kindex[i].getKmer();
		int count2 = 0;

		if (kmers2.containsKey(kmer)) {
		    count2 = ((KmerIndex)kmers2.get(kmer)).getCount();
		}

		System.out.println(kmer + "\t" + kindex[i].getCount() + "\t" + count2 + "\t" + (int)(num*kindex[i].getCount()/tot1) + "\t" + (int)(num*count2/tot2));
	    }
	    i++;
	}
    }
	
    public static void main(String[] args) {
	try {
	    String seqfile = args[0];
	    String gfffile = args[1];
	    
	    GappedFastaFile ff = new GappedFastaFile(seqfile,"File");
	    GFFFile         gff = new GFFFile(gfffile,"File");
	    
	    
	    Hashtable       fhash = gff.getFeatureHash();
	    
	    GFF             geneGff  = (GFF)fhash.get("gene");
	    
	    Vector          feat     = geneGff.getFeatures();
	    SequenceI[] s = ff.getSeqsAsArray();

	    KmerFrequency kfreq = new KmerFrequency(Integer.parseInt(args[2]),s[0],feat);
	    kfreq.index();

	    Hashtable kmerIndex1 = kfreq.getConservedKmers();
	    Hashtable kmerIndex2 = kfreq.getNonConservedKmers();

	    KmerIndex.print_kmers(kmerIndex1,kmerIndex2,0);
	} catch (IOException e) {
	    System.out.println("IOException " + e);
	}
    }

}

